package com.tourism.util;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author z
 * @Date 2021-03-08 0:19
 */
@Component
public class MailUtils {
    /**
     * 一定要用@Autowired
     */
    @Autowired
    private JavaMailSender mailSender;
    @Value("${jwt.expire.second}")
    private long expireTime;

    @Value("${spring.mail.username}")
    private String from;

    private Cache<String, String> cache;

    @PostConstruct
    public void init() {
        cache = Caffeine.newBuilder()
                //初始大小
                .initialCapacity(2)
                //最大数量
                .maximumSize(2000)
                //过期时间
                .expireAfterWrite(expireTime, TimeUnit.SECONDS)
                .build();
    }

    /**
     * 给前端输入的邮箱，发送验证码
     *
     * @param email
     * @return
     */
    public boolean sendMimeMail(String email) {
        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();


            //主题
            mailMessage.setSubject("验证码邮件");
            //生成随机数
            String code = randomCode();


            //将随机数放置到session中
            cache.put(email, code);
            //内容
            mailMessage.setText("您收到的验证码是：" + code);

            //发给谁
            mailMessage.setTo(email);

            //你自己的邮箱
            mailMessage.setFrom(from);
            //发送
            mailSender.send(mailMessage);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 检验验证码是否正确
     *
     * @param mail
     * @return
     */
    public Boolean checkCode(String mail, String code) {
        String verifyCode = cache.getIfPresent(mail);
        if (verifyCode == null) {
            return null;
        }
        return code.equals(cache.getIfPresent(mail));
    }


    /**
     * 随机生成6位数的验证码
     *
     * @return String code
     */
    public String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();

    }
}
